<template>
  <div class="category-form-component">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      class="category-form"
    >
      <div class="grid grid-cols-1 lg:grid-cols-3 gap-6">
        <!-- 左侧：可编辑信息（占 2 列） -->
        <el-card shadow="never" class="form-card lg:col-span-2">
          <template #header>
            <h3 class="text-lg font-semibold">分类信息</h3>
          </template>

          <div class="space-y-6">
            <el-form-item label="分类名称" prop="name">
              <el-input
                v-model="formData.name"
                placeholder="请输入分类名称"
                maxlength="20"
                show-word-limit
              />
            </el-form-item>

            <el-form-item label="分类代码" prop="code">
              <el-input
                v-model="formData.code"
                placeholder="请输入分类代码，如：politics"
                maxlength="50"
                show-word-limit
              />
              <div class="text-xs text-gray-500 mt-1">
                代码必须以小写字母开头，只能包含小写字母、数字和下划线
              </div>
            </el-form-item>

            <el-form-item label="排序" prop="sortOrder">
              <el-input-number
                v-model="formData.sortOrder"
                :min="1"
                :max="100"
                class="w-full"
              />
              <div class="text-xs text-gray-500 mt-1">
                数字越小越靠前
              </div>
            </el-form-item>

            <el-form-item label="状态" prop="status">
              <el-switch
                v-model="formData.status"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
              />
            </el-form-item>

            <el-form-item label="分类描述" prop="description">
              <el-input
                v-model="formData.description"
                type="textarea"
                :rows="4"
                placeholder="请输入分类描述"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </div>
        </el-card>

        <!-- 右侧：元数据（只读，占 1 列） -->
        <el-card shadow="never" class="form-card">
          <template #header>
            <h3 class="text-lg font-semibold">元数据</h3>
          </template>
          <div class="space-y-4">
            <el-descriptions :column="1" border>
              <el-descriptions-item label="ID">
                <span>{{ formData.id ?? '-' }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="创建时间">
                <span>{{ formatDateTime(formData.createdAt) }}</span>
              </el-descriptions-item>
              <el-descriptions-item label="修改时间">
                <span>{{ formatDateTime(formData.updatedAt) }}</span>
              </el-descriptions-item>
            </el-descriptions>
          </div>
        </el-card>
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'

// 定义组件属性
const props = defineProps({
  mode: {
    type: String,
    required: true,
    validator: (value) => ['add', 'edit'].includes(value)
  },
  categoryId: {
    type: [String, Number],
    default: null
  },
  initialData: {
    type: Object,
    default: () => ({})
  }
})

// 定义组件事件
const emit = defineEmits(['save', 'delete', 'cancel'])

// 表单引用
const formRef = ref()

// 表单数据
const formData = reactive({
  id: null,
  name: '',
  code: '',
  sortOrder: 1,
  status: 1,
  description: '',
  parentId: null,
  level: 1,
  path: null,
  createdAt: '',
  updatedAt: ''
})

// 表单验证规则
const formRules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入分类代码', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_]*$/, message: '代码必须以小写字母开头，只能包含小写字母、数字和下划线', trigger: 'blur' }
  ],
  sortOrder: [
    { required: true, message: '请输入排序值', trigger: 'blur' },
    { type: 'number', min: 1, max: 100, message: '排序值必须在 1 到 100 之间', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择分类状态', trigger: 'change' }
  ]
}

// 初始化表单数据
const initFormData = () => {
  if (props.mode === 'add') {
    // 新增模式：设置默认值
    Object.assign(formData, {
      id: null,
      name: '',
      code: '',
      sortOrder: 1,
      status: 1,
      description: '',
      parentId: null,
      level: 1,
      path: null,
      createdAt: '',
      updatedAt: ''
    })
  } else if (props.mode === 'edit' && props.initialData) {
    // 编辑模式：使用传入的初始数据
    Object.assign(formData, {
      id: props.initialData.id || null,
      name: props.initialData.name || '',
      code: props.initialData.code || '',
      sortOrder: props.initialData.sortOrder || 1,
      status: props.initialData.status !== undefined ? props.initialData.status : 1,
      description: props.initialData.description || '',
      parentId: props.initialData.parentId || null,
      level: props.initialData.level || 1,
      path: props.initialData.path || null,
      createdAt: props.initialData.createdAt || '',
      updatedAt: props.initialData.updatedAt || ''
    })
  }
}

// 验证表单
const validate = async () => {
  if (!formRef.value) return false
  
  try {
    const valid = await formRef.value.validate()
    return valid
  } catch (error) {
    console.error('表单验证失败:', error)
    return false
  }
}

// 获取表单数据
const getFormData = () => {
  return { ...formData }
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  initFormData()
}

// 保存分类
const handleSave = async () => {
  try {
    const valid = await validate()
    if (!valid) return false
    
    // 触发保存事件，让父组件处理
    emit('save', { ...formData })
    return true
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败，请重试')
    return false
  }
}

// 删除分类
const handleDelete = async () => {
  try {
    // 触发删除事件，让父组件处理
    emit('delete', formData.id)
  } catch (error) {
    console.error('删除失败:', error)
    ElMessage.error('删除失败，请重试')
  }
}

// 取消操作
const handleCancel = () => {
  emit('cancel')
}

// 监听初始数据变化
watch(() => props.initialData, () => {
  if (props.mode === 'edit') {
    initFormData()
  }
}, { deep: true })

// 组件初始化
onMounted(() => {
  initFormData()
})

// 暴露方法给父组件
defineExpose({
  formRef,
  formData,
  validate,
  getFormData,
  resetForm,
  handleSave,
  handleDelete,
  handleCancel
})

// 时间格式化工具
function formatDateTime(val) {
  if (!val) return '-'
  try {
    const d = new Date(val)
    if (Number.isNaN(d.getTime())) return String(val)
    const pad = (n) => String(n).padStart(2, '0')
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}:${pad(d.getSeconds())}`
  } catch {
    return String(val)
  }
}
</script>

<style scoped>
.category-form-component {
  @apply w-full;
}

.form-card {
  @apply border border-gray-200 ;
}

.form-card :deep(.el-card__header) {
  @apply bg-gray-50  border-b border-gray-200 ;
}

.category-form :deep(.el-form-item__label) {
  @apply text-gray-700  font-medium;
  line-height: 28px;
}

.category-form :deep(.el-input-number) {
  @apply w-full;
}

/* 元数据 Descriptions 更紧凑 */
.form-card :deep(.el-descriptions__label) {
  @apply w-24;
}
</style>
